<template>
  <div class="ai-chat-container">
    <!-- 消息容器 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
        <!-- 用户消息 -->
        <div v-if="msg.role === 'user'" class="user-message">
          <div class="avatar">
            <el-avatar icon="UserFilled" />
          </div>
          <div class="bubble">
            <div class="content" v-html="msg.htmlContent"></div>
          </div>
        </div>

        <!-- AI消息 -->
        <div v-else class="ai-message">
          <div class="avatar">
            <el-avatar :icon="loading && index === messages.length - 1 ? '' : 'Promotion'" />
            <div v-if="loading && index === messages.length - 1" class="loading">
              <el-icon class="is-loading"><Loading /></el-icon>
            </div>
          </div>
          <div class="bubble">
            <div class="content" v-html="msg.htmlContent"></div>
            <div v-if="msg.role === 'assistant' && !msg.finished" class="cursor">█</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="3"
        :disabled="loading"
        placeholder="请输入您的问题..."
        @keydown.enter.exact.prevent="sendMessage"
      />
      <div class="action-bar">
        <el-button
          type="primary"
          :loading="loading"
          @click="sendMessage"
          :icon="Promotion"
        >
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import 'highlight.js/styles/github-dark.css';

// 初始化 Markdown 解析器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  highlight: (str, lang) => {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs"><code>${hljs.highlight(str, {
          language: lang,
          ignoreIllegals: true
        }).value}</code></pre>`;
      } catch {}
    }
    return `<pre class="hljs"><code>${md.utils.escapeHtml(str)}</code></pre>`;
  }
});

const messages = ref([]);
const inputMessage = ref('');
const loading = ref(false);
const messagesContainer = ref(null);

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim() || loading.value) return;

  // 保存用户输入的内容
  const userInput = inputMessage.value;

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: userInput,
    htmlContent: md.render(userInput),
    finished: true
  });

  // 添加初始AI消息
  const aiMessage = {
    role: 'assistant',
    content: '',
    htmlContent: '',
    finished: false
  };
  messages.value.push(aiMessage);

  // 清空输入
  inputMessage.value = '';
  loading.value = true;
  scrollToBottom();

  // 创建 EventSource 实例
  const eventSource = new EventSource(`/demo/deepseek/stream?prompt=${encodeURIComponent(userInput)}`);

  eventSource.onmessage = (event) => {
    console.log("eventSource.onmessage event=",event)
    const data = JSON.parse(event.data);
    aiMessage.content += data.content;
    aiMessage.htmlContent = md.render(aiMessage.content);
    scrollToBottom();
    highlightCode();
  };

  eventSource.onerror = (error) => {
    console.error('EventSource failed:', error);
    ElMessage.error('请求失败: ' + error.message);
    eventSource.close();
    loading.value = false;
  };
};

// 代码高亮
const highlightCode = () => {
  nextTick(() => {
    document.querySelectorAll('pre code').forEach(block => {
      hljs.highlightElement(block);
    });
  });
};
</script>

<style scoped>
.ai-chat-container {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  border-radius: 8px;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: white;
}

.message {
  margin: 15px 0;
}

.user-message, .ai-message {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.ai-message {
  margin-right: auto;
}

.avatar {
  flex-shrink: 0;
}

.bubble {
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  max-width: 700px;
  position: relative;
}

.ai-message .bubble {
  background: #f9fafb;
  border: 1px solid #e5e7eb;
}

.content {
  line-height: 1.6;
  font-size: 14px;
}

.cursor {
  display: inline-block;
  animation: blink 1s infinite;
  color: #409eff;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

.input-area {
  padding: 20px;
  background: white;
  border-top: 1px solid #ebeef5;
}

.action-bar {
  margin-top: 10px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.loading {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* Markdown样式 */
:deep(.hljs) {
  padding: 1em;
  border-radius: 6px;
  margin: 1em 0;
}

:deep(blockquote) {
  border-left: 4px solid #ddd;
  padding-left: 1em;
  color: #666;
}

:deep(table) {
  border-collapse: collapse;
  margin: 1em 0;
}

:deep(th), :deep(td) {
  border: 1px solid #ddd;
  padding: 8px;
}
</style>
